package com.bbx.taxi.client.Activity.Wallet;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.Config;
import com.bbx.api.util.LogUtils;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Bean.Extra.ContactPersonMsg;
import com.bbx.taxi.client.Bean.Extra.RecommenMsg;
import com.bbx.taxi.client.Bean.Extra.ShareCouponMsg;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.widget.pop.SharePopView;
import com.umeng.socialize.bean.SHARE_MEDIA;

import butterknife.Bind;

/**
 * 作者：严旭文 on 2016/12/26 09:28
 * 邮箱：420255048@qq.com
 */
public class ShareCouponActivity extends BaseBBXActivity {
    @Bind(R.id.webview)
    WebView webview;
    /**分享POP*/
    public SharePopView mSharePopView;
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_recommen);
        super.onCreate(savedInstanceState);

    }
    @Override
    protected void initView() {
        if(loaddialog!=null&&!loaddialog.isShowing())loaddialog.show();
        setTitle("优惠劵赠送");
    }

    @Override
    protected void initData() {
        mSharePopView=new SharePopView(context,null);
        webview.getSettings().setAllowFileAccess(true);
        //如果访问的页面中有Javascript，则webview必须设置支持Javascript
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setAppCacheEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setDatabaseEnabled(true);
        webview.getSettings().setGeolocationEnabled(true);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setSupportZoom(true);
        String couponid="";
        Intent intent = getIntent();
        if (intent.getExtras() != null) {
            couponid = intent.getExtras().getString(
                    ShareCouponMsg.extra_couponid);
        }
        if(couponid==null||couponid.equals(""))return;
        // 获取本地存储的电话
        String tel = SharedPreUtil.getStringValue(this,
                SharedPreEncryptUtil.phone, "");
        // 获取名字
        String name= SharedPreUtil.getStringValue(this,
                SharedPreEncryptUtil.user_name, "");
        String access_token;
        try {
            access_token = new String(java.net.URLEncoder.encode(mApplication.getToken(), "UTF-8").getBytes(), "ISO-8859-1");
        } catch (Exception e) {
            access_token=mApplication.getToken();
        }
        switch(Config.getInstance().Env){
            case 0:
//				huanjing="环境：开发";
                break;
            case 1://测试
                String ceshiurl="http://weixin.bbxpc.com/wxtest/user"+"?method=initShareCoupon&uid="+mApplication.getUid()+"&access_token="+access_token+"&couponId="+couponid+"&name="+name+"&tel="+tel;
                LogUtils.e("xxx", ceshiurl + "");
                webview.loadUrl(ceshiurl);
                break;
            case 2://正式
                String zhengshiurl="http://weixin.bbxpc.com/user"+"?method=initShareCoupon&uid="+mApplication.getUid()+"&access_token="+access_token+"&couponId="+couponid+"&name="+name+"&tel="+tel;
                LogUtils.e("xxx",zhengshiurl+"");
                webview.loadUrl(zhengshiurl);
                break;
        }
        //加载assets目录下面的demo.html 界面
//	        webview.loadUrl("file:///android_asset/demo.html");
        //增加接口方法,让html页面调用
        webview.addJavascriptInterface(this, "ncp");
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                if (loaddialog != null) {
                    loaddialog.dismiss();
                }
                webview.setVisibility(View.VISIBLE);
                super.onPageFinished(view, url);
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    return false;
                }

                // Otherwise allow the OS to handle things like tel, mailto, etc.
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }
        });
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin,
                                                           android.webkit.GeolocationPermissions.Callback callback) {
                // TODO Auto-generated method stub
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                callback.invoke(origin, true, false);
            }
        });
    }
    @JavascriptInterface
    public void shareCoupon(final String type,final String url, final String wxDesc, final String wxTitle){
        new AsyncTask<Void, Void, Void>(){

            @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                LogUtils.e("xxx",type+","+url+","+wxDesc+","+wxTitle);
                if(type.equals("weixin")){
                    mSharePopView.performShare(SHARE_MEDIA.WEIXIN, url,wxTitle,wxDesc,R.drawable.icon_sharecoupon);
                }else if(type.equals("friend")){
                    mSharePopView. performShare(SHARE_MEDIA.WEIXIN_CIRCLE,  url,wxTitle,wxDesc,R.drawable.icon_sharecoupon);
                }
                else if(type.equals("xinlang")){
                    mSharePopView. performShare(SHARE_MEDIA.SINA,url,wxTitle,wxDesc,R.drawable.icon_sharecoupon);
                }
                super.onPostExecute(result);
            }

        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                if(webview.canGoBack()){
                    webview.goBack();
                }else{
                    Intent intent = new Intent();
                    setResult(resultCode, intent);
                    finish();
                }
                break;
            default:
                super.onClick(v);
                break;
        }

    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(webview.canGoBack()){
                webview.goBack();
            }else{
                Intent intent = new Intent();
                setResult(resultCode, intent);
                finish();
            }

            return true;

        }
        return false;
    }
}
